<?php
namespace App\Api\Controllers;
use Common\ApiController;
use Common\BaseController;
use Common\Common;
use Common\Models\Codes;
use Common\Models\User;
use Common\Models\UserLoginlog;
use Library\Tools\JwtTools;

/**
 * @class 获取验证码-登录相关的接口
 */
class Login2Controller extends BaseController
{
    public function initialize()
    {
        parent::initialize();
    }


    /**
     * @func 发送验证码
     * @return json
     */
    public function send_codeAction()
    {
        $params = $this->request();
        if (!isset($params['phone']) || empty($params['phone'])) {
            $this->fail(-1, '手机号码不能为空');
        } else {
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $params['phone'])) {
                $this->fail(-1, '手机号码错误');
            }
        }

//        $rand_code = rand(111111, 999999);
//        $code       = new Codes();
//        $find_phone = $code->find_by_phone($params['phone']);
        if (!isset($params['type']) || empty($params['type'])) {
            $params['type'] = 1;
        }

        $user       = new User();
        $user_phone = $user->find_by_phone($params['phone']);
        if ($user_phone) {
            if ($user_phone['is_disable']) {
                $this->fail(-1, '违规账号已冻结');
            }
        }
        if ($params['type'] == 1) {           //注册
            if (!isset($params['source']) || empty($params['source'])) {      //网页端注册没有传平台
                if ($user_phone) {
                    $this->fail(-1, '该手机已经存在');
                }
            }
            $template_type = 1;
            $title         = "注册验证";
        } elseif ($params['type'] == 2) {     //登录
            $template_type = 2;
            $title         = "登录验证";
        } elseif ($params['type'] == 3) {      //变更信息
            $template_type = 3;
            $title         = "变更验证";
        }  elseif ($params['type'] == 4) {      //变更信息
            $template_type = 3;
            $title         = "验证验证码";
        } else {
            $this->fail(-1, 'type参数错误');
        }

//        if (strtotime($find_phone['expire_at']) > time()) {
//            $this->fail(-1, '验证码发送太频繁，请稍后发送');
//        }

//        $data['id']         = $find_phone['id'];
//        $data['created_at'] = $find_phone['created_at'];
//        $data['updated_at'] = date('Y-m-d H:i:s', time());
//        $data['recipient']  = $params['phone'];
//        $data['code']       = $rand_code;
//        $data['expire_at']  = date('Y-m-d H:i:s', time() + 1 * 60);//5分钟有效
//        $result_code        = $code->save_codes($data);
//        $sms_result = $this->sms->send($params['phone'], $title, $rand_code, $template_type);

        $sms_result = $this->jpush->jgsms($params['phone']);
        if ($sms_result['code']) {
            $resumt['msg_id'] = $sms_result['data'];
            $this->ok($resumt);
        } else {
            $this->fail(-1, $sms_result['msg']);
        }
    }


    /**
     * 验证短信验证码 H5拉新页面
     */
    public function validate_phone_codeAction()
    {
        $request = new Request();
        if ($request->isPost() != true) {
            return $this->fail(-1, '请求方式错误');
        }
        $params = $this->request->getPost();
        //手机验证码登录
        if (!isset($params['phone']) || empty($params['phone'])) {
            $this->fail(-1, '手机号码不能为空');
        } else {
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $params['phone'])) {
                $this->fail(-1, '手机号码错误');
            }
        }
        if (!isset($params['smscode']) || empty($params['smscode'])) {
            $this->fail(-1, '验证码不能为空');
        }
        $code_obj        = new Codes();
        $find_code_phone = $code_obj->find_by_phone($params['phone']);
        if ($find_code_phone) {
            if (strtotime($find_code_phone['expire_at']) < time()) {
                $this->fail(-1, '验证码过期，请从新获取');
            }
            if ($find_code_phone['code'] != $params['smscode']) {
                $this->fail(-1, '验证码输入错误');
            }
        } else {
            $this->fail(-1, '请获取验证码');
        }
        $this->ok([]);
    }


    /**
     * 微信登录
     */
    public function loginwxAction()
    {
        $params = array_merge($this->request->get(), $this->request->getPost());
        if (!isset($params['union_id']) || empty($params['union_id'])) {
            $this->fail(-1, '请传入微信union_id');
        }
        $users      = new User();
        $users_info = $users->find_by_wxaccount($params['union_id']);

        if (empty($users_info)) {
            $this->fail(3, '对不起，该微信未注册');
        }
        if (empty($users_info['phone'])) {
            $this->fail(2, '对不起，该微信已注册，但是还没有绑定手机');
        }

        $users_info['is_appuser'] = 1;
        $user_save                = new User();
        $user_save->save_user($users_info);

        $this->ok($users_info);
    }


    /**
     * @func 登录
     */
    public function loginAction()
    {
        $user    = new User();
        $params = $this->request();
        //手机验证码登录

        if (isset($params['token']) && !empty($params['token'])) {
            $params['phone'] = $this->jiguang($params['token']);  //极光一键登录
            //$params['phone']='17623536980';
        } else {
            if (!isset($params['phone']) || empty($params['phone'])) {
                $this->fail(-1, '手机号码不能为空');
            } else {
                if (!preg_match("/^1[3456789]{1}\d{9}$/", $params['phone'])) {
                    $this->fail(-1, '手机号码错误');
                }
            }
        }


        /**
         * ios审核模式
         */
        if ($params['source'] != 'ios' || $params['phone'] != '17623536980') {
            if ((!isset($params['token']) || empty($params['token'])) && (!isset($params['pwd']) || empty($params['pwd']))) {
                if ((!isset($params['smscode']) || empty($params['smscode'])) && (!isset($params['msg_id']) || empty($params['msg_id']))) {
                    $this->fail(-1, '验证码和短信模板id不能为空');
                }
                $check_smg = $this->jpush->jgcheckcode($params['msg_id'], $params['smscode']);
                if (!$check_smg['code']) {
                    //验证内置邀请码 等于用户账号排查问题
                    $code_obj = new Codes();
                    $find_code_phone = $code_obj->find_by_phone($params['phone']);
                    if ($find_code_phone) {
                        if (strtotime($find_code_phone['expire_at']) < time()){
                            $this->fail(-1, $check_smg['msg']);
                        }
                        if ($find_code_phone['code'] != $params['smscode']) {
                            $this->fail(-1, $check_smg['msg']);
                        }
                    }
                }
            }
        }

        $data = $user->find_by_phone($params['phone']);
        if (empty($data)) {
            $data['phone']       = $params['phone'];
            $data['referer_id']  = 1005;
            $data['path']        = 0;
            $data['invite_code'] = '';
            $data['created_at']  = date('Y-m-d H:i:s');
            $child_flag          = true;        //是否有下级用户 没有下级
        } else {
            if (isset($params['pwd']) && !empty($params['pwd'])) {
                if ($data['password'] != md5(md5($params['pwd']))) {
                    $this->fail(-1, '密码输入错误');
                }
            }
            if ($data['is_disable'] == 1) {
                $this->fail(-1, '该账号由于违规操作，已经被禁用');
            }

            if((isset($params['union_id']) && !empty($params['union_id'])) && !empty($data['wx_account'])){
                if($params['union_id'] != $data['wx_account']){
                    $this->fail(-1,'该手机号码已经绑定了微信');
                }
            }

            $directuser                 = new User();
            $datetime['start_end_time'] = [];
            $directFanscount            = $directuser->getDirectFansCount($data['id'], $datetime);
            if ($directFanscount) {       //找到下级
                $child_flag = false;    //有下级
            } else {
                $child_flag = true;     //没有下级
            }

        }

        if (empty($data['invite_code']) && isset($params['invite_code']) && !empty($params['invite_code'])) {            //用户填入邀请码
            if (empty($data['invite_code']) && $child_flag) {
                $invite_user = $user->find_by_inviteCode($params['invite_code']);
                if (empty($invite_user)) {
                    $this->fail(-1, '邀请码不存在');
                }
                if (empty($invite_user['invite_code']) || empty($invite_user['phone'])) {
                    $this->fail(-1, '该邀请码不是有效的会员');
                }
                $data['referer_id'] = $invite_user['id'];
                if ($invite_user['path'] == '') {
                    $data['path'] = $invite_user['referer_id'];
                    $data['indirect_id'] = $invite_user['referer_id'];
                } else {
                    $data['path'] = $invite_user['path'] . ',' . $invite_user['referer_id'];
                    $data['indirect_id'] = $invite_user['referer_id'];
                }
                $invitecode          = new InviteCodes();
                $data['invite_code'] = $invitecode->usedInviteCode();       //创建邀请码

                //2020/3/23  潜在粉丝注册成长值
                //$user->growth_value(12,$data['referer_id']);
                $idArr = explode(",", $data['path']);
                $last = end($idArr);
                if($last){
                    //$user->growth_value(13,$last);
                }
            }
        }


        if (isset($params['union_id']) && !empty($params['union_id'])) {                  //用户传入了微信号码
            $wx_userobj   = new User();
            $wx_user_info = $wx_userobj->find_by_wxaccount($params['union_id']);
            if ($wx_user_info) {                                                       //微信存在的时候

                if (isset($data['wx_account']) && !empty($data['wx_account'])) {     //判断当前登录的手机是否已经绑定了
                    $this->fail(-1, '该手机号已经绑定了微信');
                }

                if ($wx_user_info['phone']) {                                       //判断该微信的手机是否已经绑定
                    $this->fail(-1, '该微信已经绑定了手机账号');
                }

                if (empty($data['invite_code']) && $child_flag) {       //如果手机号码存在邀请码
                    $data['referer_id']  = $wx_user_info['referer_id'];
                    $data['path']        = $wx_user_info['path'];
                    $data['invite_code'] = $wx_user_info['invite_code'];
                }


                $write       = '删掉的微信：' . json_encode($wx_user_info) . '写入的日期：' . date('Y-m-d H:i:s', time()) . "\n";
                $create_file = '../cache/reg_del_' . $wx_user_info['invite_code'] . '.log';       //创建文件
                file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
                $wx_user        = new User();
                $dele_wxaccount = $wx_user->find_by_wxaccountobj($params['union_id']);
                $del_result     = $dele_wxaccount->delete();
                if ($del_result) {
                    $wallets      = new Wallets();
                    $wallets_user = $wallets->findbyUserId($wx_user_info['id']);
                    $wallets_user->delete();
                }
                $invitecode           = new InviteCodes();
                $wxaccount_invitecode = $invitecode->findbyId($wx_user_info['invite_code']);
                if ($wxaccount_invitecode) {
                    if ($wxaccount_invitecode['used'] == 1) {
                        $wxaccount_invitecode['used'] = 0;
                        $invitecode->save_invite($wxaccount_invitecode);
                    }
                }
            }

            $data['wx_account']  = $params['union_id'];
            $data['wx_nickname'] = (isset($params['nickname']) && !empty($params['nickname'])) ? $params['nickname'] : '';
            $data['avatar']      = (isset($params['avatar']) && !empty($params['avatar'])) ? $params['avatar'] : '';
            $data['gender']      = (isset($params['gender']) && !empty($params['gender'])) ? $params['gender'] : '';
        }


        if ((isset($params['invite_code']) && !empty($params['invite_code'])) && (isset($params['union_id']) && !empty($params['union_id']))) {                            //存在邀请码和存在微信

            if (empty($data['invite_code']) && $child_flag) {
                $invite_user = $user->find_by_inviteCode($params['invite_code']);
                if (empty($invite_user)) {
                    $this->fail(-1, '邀请码不存在');
                }
                if (empty($invite_user['invite_code']) || empty($invite_user['phone'])) {
                    $this->fail(-1, '该邀请码不是有效的会员');
                }
                if (empty($params['invite_code'])) {
                    $data['referer_id'] = $invite_user['id'];
                    if ($invite_user['path'] == '') {
                        $data['path'] = $invite_user['referer_id'];
                    } else {
                        $data['path'] = $invite_user['path'] . ',' . $invite_user['referer_id'];
                    }
                    $invitecode          = new InviteCodes();
                    $data['invite_code'] = $invitecode->usedInviteCode();       //创建邀请码
                }
            }

            $data['wx_account']  = $params['union_id'];
            $data['wx_nickname'] = (isset($params['nickname']) && !empty($params['nickname'])) ? $params['nickname'] : '';
            $data['avatar']      = (isset($params['avatar']) && !empty($params['avatar'])) ? $params['avatar'] : '';
            $data['gender']      = (isset($params['gender']) && !empty($params['gender'])) ? $params['gender'] : '';
        }
        if (isset($params['is_appuser'])) {           //记录app端注册还是h5注册 h5传入了，app没有传入
            $data['is_appuser'] = 0;
        } else {
            $data['is_appuser'] = 1;
        }

        $usernew = new User();
        $result  = $usernew->save_user($data);
        if ($result) {
            Common::invite($data['referer_id'], $data['path']);        //直邀，间邀，团队人数累加
            $iat = time();
            $loginData['token_expired'] = date('Y-m-d H:i:s', $iat);
            $token = (new JwtTools())->getToken($data['id'], $iat, 'app');
            $loginData['token'] = $token;
            $this->ok($loginData);
        } else {
            $this->fail(-1, '用户创建失败，请重试');
        }

    }


    /**
     * @func 极光一键登录
     */
    public function jiguang($jg_token)
    {
        if (!isset($jg_token) || empty($jg_token)) {
            $this->fail(-1, 'token不能为空');
        }
        //获取手机号
        $token  = trim($jg_token);
        $header = ['Authorization:' . 'Basic ' . base64_encode('b712ad86770b1084257061d2:eb6887b22613835a76e69c28'), 'Content-Type:' . 'application/json'];
        $url    = 'https://api.verification.jpush.cn/v1/web/loginTokenVerify';
        $data   = ['loginToken' => $token];
        $curl   = curl_init();
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_HEADER, 0);//返回response头部信息
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HTTPGET, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        $res = json_decode($output, true);
        if (!isset($res['phone']) || empty($res['phone'])) {
            $this->fail(-1, '获取手机号码失败');
        }
        $encrypted = $res['phone'];

        //解密
        $privateKey = '-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALtn/MRBNZgxffHU
morVDaRc0qyKnKt6tkMwQ4/tPZPiJw9ATcFqJOPVg72GCIp8sF1/oGybG26w0u/+
YJuOmK89P9DInlcINBpiDoC86vJwykxiMvkHa9FOEuUfPfCTpDJdmNBkn/sY7Rii
SC2Bi5nDYt8ie8ZgvTJAT7P0x+ijAgMBAAECgYAnDYdt+kzJ115we6Zs0fMS0kkQ
rZ3yWhMLM06Q+pY/b/xFwFezu4POepsGbpzvBwbVpRfwKe5whaafXnoRUIjeeBiE
ULWPoj7LddRaWwIm6oqL3h8ri+Yp4SHIiX2JHWYAWD6DwJkM1YDvYxGnHsg4lx9u
P9i/Xq/y0xITRau7UQJBAO8SbtxDa78c2qyBi6w30lA0xjLe+iGVkMTtXp/9pCCz
OQNkPV3T+J+ooOUb0w28z7lsp1BwkEnrKh27wjH6MgsCQQDIrQcstX0DM5jGB+u5
NRrA03zDK0AXbDwWbwfVC6bDcuGndL0IK0NzvfS2KXG+hNCJdvOVZ2Ucs0yXYTIB
NJrJAkBH+RKq+Rks9fDXUkDMXhnQz7KDiiFfjvmAb723CNMqjQoy/TCEWNZWqpuV
neTSE++tcQqF6v1lY4jQXsA974a1AkEAw7M50/gJuh2PV1BSKYQIWxPkD9EV58G9
t4L/+FwsfV6DgXLvBhBq72zIQP2Z11pepDBEy+bRTHPutZIr2dEbQQJAYYptMwPO
353WSjHW4XlOGjK1uhNr54bzslhZnSsyFxWzAGIrVWKSZOmtpR7U4wm1u+9k/MQt
fTqIuMSb1k3fCw==
-----END PRIVATE KEY-----';
        $r          = openssl_private_decrypt(base64_decode($encrypted), $phone, openssl_pkey_get_private($privateKey));
        if (!preg_match("/^1[3456789]{1}\d{9}$/", $phone)) {
            $this->fail(-1, '手机号码错误');
        }
        return $phone;
    }





    /**
     * @func 注册
     */
    public function registerAction()
    {
        $data['referer_id']  = '2';
        $data['path']        = '0,1';
        $data['invite_code'] = '';
        $data['created_at']  = date('Y-m-d H:i:s');
        $data['updated_at']  = date('Y-m-d H:i:s');
        $UserDb = new User();
        if(!isset($this->params['phone']) || empty($this->params['phone'])){
            $this->fail(-1,'电话号码不能为空');
        }else{
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $this->params['phone'])) {
                $this->fail(-1, '手机号码错误');
            }
            $user_find_one = $UserDb->find_by_phone($this->params['phone']);
            if(!$user_find_one){
                $this->fail(-1,'账号已经存在，请直接登录');
            }
        }
        $data['phone'] = $this->params['phone'];
        $data['nickname'] = substr_replace($this->params['phone'], '****', 3, 4);

        if ((!isset($this->params['smscode']) || empty($this->params['smscode'])) && (!isset($this->params['msg_id']) || empty($this->params['msg_id']))) {
            $this->fail(-1, '验证码和短信模板id不能为空');
        }
        $check_smg = $this->jpush->jgcheckcode($this->params['msg_id'], $this->params['smscode']);
        if (!$check_smg['code']) {
            //验证内置邀请码 等于用户账号排查问题
            $code_obj = new Codes();
            $find_code_phone = $code_obj->find_by_phone($this->params['phone']);
            if ($find_code_phone) {
                if (strtotime($find_code_phone['expire_at']) < time()){
                    $this->fail(-1, $check_smg['msg']);
                }
                if ($find_code_phone['code'] != $this->params['smscode']) {
                    $this->fail(-1, $check_smg['msg']);
                }
            }
        }

        if(!isset($this->params['pwd']) || empty($this->params['pwd'])){
            $this->fail(-1,'密码不能为空');
        }else{
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $this->params['pwd'])) {
                $this->fail(-1, '手机号码错误');
            }
        }

        if(!isset($this->params['re_pwd']) || empty($this->params['re_pwd'])){
            $this->fail(-1,'重复密码不能为空');
        }else{
            if(md5($this->params['re_pwd']) != md5($this->params['pwd'])){
                $this->fail(-1,'两次密码输入不一致');
            }
        }
        $data['password'] = md5($this->params['pwd']);

        if(!isset($this->params['invite_code']) || empty($this->params['invite_code'])){
            $this->fail(-1,'邀请码不能为空');
        }

        if (empty($data['invite_code']) && isset($params['invite_code']) && !empty($params['invite_code'])) {            //用户填入邀请码
            $invite_user = $UserDb->find_by_inviteCode($params['invite_code']);
            if (empty($invite_user)) {
                $this->fail(-1, '邀请码不存在');
            }
            if (empty($invite_user['invite_code']) || empty($invite_user['phone'])) {
                $this->fail(-1, '该邀请码不是有效的会员');
            }
            $data['referer_id'] = $invite_user['id'];
            if ($invite_user['path'] == '') {
                $data['path'] = $invite_user['referer_id'];
                $data['indirect_id'] = $invite_user['referer_id'];
            } else {
                $data['path'] = $invite_user['path'] . ',' . $invite_user['referer_id'];
                $data['indirect_id'] = $invite_user['referer_id'];
            }
            $invitecode          = new InviteCodes();
            $data['invite_code'] = $invitecode->usedInviteCode();       //创建邀请码
        }
        if($UserDb->save_user($data)){
            $this->ok([]);
        }
        $this->fail(-1,'网络异常');

    }




    /**
     * @func 密码登录
     */
    public function passwordAction()
    {
        $params = $this->request();
        //手机验证码登录
        if (!isset($params['phone']) || empty($params['phone'])) {
            $this->fail(-1, '手机号码不能为空');
        } else {
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $params['phone'])) {
                $this->fail(-1, '手机号码错误');
            }
        }
        if (!isset($params['pwd']) || empty($params['pwd'])) {
            $this->fail(-1, '密码不能为空');
        } else {
            $pattern = '/^[0-9a-z_$]{6,16}$/i'; // i 不区分大小写
            if (!preg_match($pattern, $params['pwd'])) {
                $this->fail(-1, '密码只能是数字加字母，长度6-16位');
            }
        }

        $this->login($params, 1);
    }

    /**
     * @func 登录
     * @param $params array //参数
     * @param $type  int //登录方式 1密码+手机号 2 极光一键登录
     * @return mixed
     */

    private function login($params, $type = 1)
    {
        $user = new User();
        $data = $user->find_by_phone($params['phone']);
        if (empty($data)) {
            $this->fail(-1, '该手机号未注册');
        }

        if ($data['is_disable'] == 1) {
            $this->fail(-1, '该账号由于违规操作，已经被禁用');
        }
        if ($type == 1) {
            if (empty($data['password'])) {
                $this->fail(-1, '该账号未设置密码');
            }
            if (md5(md5($params['pwd'])) != $data['password']) {
                $this->fail(-1, '密码错误');
            }
        }

        $datetime['start_end_time'] = [];
        $directFanscount            = $user->getDirectFansCount($data['id'], $datetime);
        if ($directFanscount) {       //找到下级
            $child_flag = false;    //有下级
        } else {
            $child_flag = true;     //没有下级
        }

        $user_login_log = new UserLoginlog();
        $user_login_log->loginlog_save($data['phone']);

        if (empty($data['invite_code'])) {
            $this->ok([], 4);
        }
        unset($data['password']);
        $this->ok($data);
    }

    /**
     * 根据邀请码获取上级邀请人
     */
    public function comforimAction()
    {
        $params = $this->request();
        if (!isset($params['invite_code']) || empty($params['invite_code'])) {
            $this->fail(-1, '请输入邀请码');
        }
        $user        = new User();
        $invite_user = $user->find_by_inviteCode($params['invite_code']);
        if (empty($invite_user)) {
            $this->fail(-1, '没有找到上级邀请人');
        }
        if (empty($params['invite_code']) || empty($invite_user['phone'])) {
            $this->fail(-1, '该邀请码不是有效的邀请人');
        }

        if ($invite_user['nickname'] || $invite_user['wx_nickname'] || $invite_user['phone']) {             //获取当前我的昵称 判断 以前的nickname 后面添加了一个wx_nickname 如果没有的话就取电话号码
            $username = $invite_user['nickname'] ? $invite_user['nickname'] : $invite_user['wx_nickname'];
            if (empty($username)) {
                $phone = substr_replace($invite_user['phone'], '****', 3, 4);
                $username = $phone;
            }
        } else {
            $username = '没有填写';
        }

        $data['id']       = $invite_user['id'];
        $data['nickname'] = $username;
        $data['avatar']   = $invite_user['avatar'];
        $data['invite_code'] = $invite_user['invite_code'];
        $this->ok($data);
    }




    /**
     * @func 登录
     */
    public function loginnewAction()
    {
        $params = $this->request();
        //手机验证码登录

        $user    = new User();
        if (isset($params['token']) && !empty($params['token'])) {
            $params['phone'] = $this->jiguang($params['token']);  //极光一键登录
            //$params['phone']='17623536980';
        } else {
            if (!isset($params['phone']) || empty($params['phone'])) {
                $this->fail(-1, '手机号码不能为空');
            } else {
                if (!preg_match("/^1[3456789]{1}\d{9}$/", $params['phone'])) {
                    $this->fail(-1, '手机号码错误');
                }
            }
        }


        /**
         * ios审核模式
         */
        if ($params['source'] != 'ios' || $params['phone'] != '17623536980') {


//            $check_smg = $this->jpush->jgcheckcode($params['msg_id'], $params['smscode']);
//            if (!$check_smg['code']) {
//                $this->fail(-1, $check_smg['msg']);
//            }



            if ((!isset($params['token']) || empty($params['token'])) && (!isset($params['pwd']) || empty($params['pwd']))) {

                if ((!isset($params['smscode']) || empty($params['smscode'])) && (!isset($params['msg_id']) || empty($params['msg_id']))) {
                    $this->fail(-1, '验证码和短信模板id不能为空');
                }
                $check_smg = $this->jpush->jgcheckcode($params['msg_id'], $params['smscode']);
                if (!$check_smg['code']) {

                    //验证内置邀请码 等于用户账号排查问题
                    $code_obj = new Codes();
                    $find_code_phone = $code_obj->find_by_phone($params['phone']);
                    if ($find_code_phone) {
                        if (strtotime($find_code_phone['expire_at']) < time()){
                            $this->fail(-1, $check_smg['msg']);
                        }
                        if ($find_code_phone['code'] != $params['smscode']) {
                            $this->fail(-1, $check_smg['msg']);
                        }
                    }

                }
            }

        }

        $data = $user->find_by_phone($params['phone']);
        if (empty($data)) {
            $data['phone']       = $params['phone'];
            $data['referer_id']  = 1005;
            $data['path']        = 0;
            $data['invite_code'] = '';
            $data['created_at']  = date('Y-m-d H:i:s');
            $child_flag          = true;        //是否有下级用户 没有下级
        } else {
            if (isset($params['pwd']) && !empty($params['pwd'])) {
                if ($data['password'] != md5(md5($params['pwd']))) {
                    $this->fail(-1, '密码输入错误');
                }
            }
            if ($data['is_disable'] == 1) {
                $this->fail(-1, '该账号由于违规操作，已经被禁用');
            }

            if((isset($params['union_id']) && !empty($params['union_id'])) && !empty($data['wx_account'])){
                if($params['union_id'] != $data['wx_account']){
                    $this->fail(-1,'该手机号码已经绑定了微信');
                }
            }



            $directuser                 = new User();
            $datetime['start_end_time'] = [];
            $directFanscount            = $directuser->getDirectFansCount($data['id'], $datetime);
            if ($directFanscount) {       //找到下级
                $child_flag = false;    //有下级
            } else {
                $child_flag = true;     //没有下级
            }

        }

        if (isset($params['invite_code']) && !empty($params['invite_code'])) {            //用户填入邀请码
            if (empty($data['invite_code']) && $child_flag) {
                $invite_user = $user->find_by_inviteCode($params['invite_code']);
                if (empty($invite_user)) {
                    $this->fail(-1, '邀请码不存在');
                }
                if (empty($invite_user['invite_code']) || empty($invite_user['phone'])) {
                    $this->fail(-1, '该邀请码不是有效的会员');
                }
                $data['referer_id'] = $invite_user['id'];
                if ($invite_user['path'] == '') {
                    $data['path'] = $invite_user['referer_id'];
                } else {
                    $data['path'] = $invite_user['path'] . ',' . $invite_user['referer_id'];
                }
                $invitecode          = new InviteCodes();
                $data['invite_code'] = $invitecode->usedInviteCode();       //创建邀请码

                //2020/3/23  潜在粉丝注册成长值
//                $user->growth_value(12,$data['referer_id']);
//                $idArr = explode(",", $data['path']);
//                $last = end($idArr);
//                if($last){
//                    $user->growth_value(13,$last);
//                }
            }
        }


        if (isset($params['union_id']) && !empty($params['union_id'])) {                  //用户传入了微信号码
            $wx_userobj   = new User();
            $wx_user_info = $wx_userobj->find_by_wxaccount($params['union_id']);
            if ($wx_user_info) {                                                       //微信存在的时候

                if (isset($data['wx_account']) && !empty($data['wx_account'])) {     //判断当前登录的手机是否已经绑定了
                    $this->fail(-1, '该手机号已经绑定了微信');
                }

                if ($wx_user_info['phone']) {                                       //判断该微信的手机是否已经绑定
                    $this->fail(-1, '该微信已经绑定了手机账号');
                }

                if (empty($data['invite_code']) && $child_flag) {       //如果手机号码存在邀请码
                    $data['referer_id']  = $wx_user_info['referer_id'];
                    $data['path']        = $wx_user_info['path'];
                    $data['invite_code'] = $wx_user_info['invite_code'];
                }


                $write       = '删掉的微信：' . json_encode($wx_user_info) . '写入的日期：' . date('Y-m-d H:i:s', time()) . "\n";
                $create_file = '../cache/reg_del_' . $wx_user_info['invite_code'] . '.log';       //创建文件
                file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
                $wx_user        = new User();
                $dele_wxaccount = $wx_user->find_by_wxaccountobj($params['union_id']);
                $del_result     = $dele_wxaccount->delete();
                if ($del_result) {
                    $wallets      = new Wallets();
                    $wallets_user = $wallets->findbyUserId($wx_user_info['id']);
                    $wallets_user->delete();
                }
                $invitecode           = new InviteCodes();
                $wxaccount_invitecode = $invitecode->findbyId($wx_user_info['invite_code']);
                if ($wxaccount_invitecode) {
                    if ($wxaccount_invitecode['used'] == 1) {
                        $wxaccount_invitecode['used'] = 0;
                        $invitecode->save_invite($wxaccount_invitecode);
                    }
                }
            }

            $data['wx_account']  = $params['union_id'];
            $data['wx_nickname'] = (isset($params['nickname']) && !empty($params['nickname'])) ? $params['nickname'] : '';
            $data['avatar']      = (isset($params['avatar']) && !empty($params['avatar'])) ? $params['avatar'] : '';
            $data['gender']      = (isset($params['gender']) && !empty($params['gender'])) ? $params['gender'] : '';
        }


        if ((isset($params['invite_code']) && !empty($params['invite_code'])) && (isset($params['union_id']) && !empty($params['union_id']))) {                            //存在邀请码和存在微信

            if (empty($data['invite_code']) && $child_flag) {
                $invite_user = $user->find_by_inviteCode($params['invite_code']);
                if (empty($invite_user)) {
                    $this->fail(-1, '邀请码不存在');
                }
                if (empty($invite_user['invite_code']) || empty($invite_user['phone'])) {
                    $this->fail(-1, '该邀请码不是有效的会员');
                }
                if (empty($params['invite_code'])) {
                    $data['referer_id'] = $invite_user['id'];
                    if ($invite_user['path'] == '') {
                        $data['path'] = $invite_user['referer_id'];
                    } else {
                        $data['path'] = $invite_user['path'] . ',' . $invite_user['referer_id'];
                    }
                    $invitecode          = new InviteCodes();
                    $data['invite_code'] = $invitecode->usedInviteCode();       //创建邀请码
                }
            }

            $data['wx_account']  = $params['union_id'];
            $data['wx_nickname'] = (isset($params['nickname']) && !empty($params['nickname'])) ? $params['nickname'] : '';
            $data['avatar']      = (isset($params['avatar']) && !empty($params['avatar'])) ? $params['avatar'] : '';
            $data['gender']      = (isset($params['gender']) && !empty($params['gender'])) ? $params['gender'] : '';
        }



        if (isset($params['is_appuser'])) {           //记录app端注册还是h5注册 h5传入了，app没有传入
            $data['is_appuser'] = 0;
        } else {
            $data['is_appuser'] = 1;
        }
        $usernew = new User();
        $result  = $usernew->save_user($data);
        if ($result) {
            CommonController::invite($data['referer_id'], $data['path']);        //直邀，间邀，团队人数累加
            $user_login_log = new UserLoginlog();
            $user_login_log->loginlog_save($data['phone']);
            $user1 = new User();
            $info  = $user1->find_by_phone($data['phone']);
            if (empty($info['invite_code'])) {
                $this->ok($info, 4);
            }
            $info = CommonController::get_username_phone($info['id']);
            $this->ok($info);
        } else {
            $this->fail(-1, '用户创建失败，请重试');
        }

    }


    //根据手机号查找用户
    public function find_phoneAction(){
        if(!isset($this->params['phone']) || empty($this->params['phone'])){
            $this->fail(-1,'手机号码不能为空');
        }
        $user = new User();
        $info = $user->find_by_phone($this->params['phone']);
        if($info){
            $data['invite_code']=$info['invite_code'];
        }else{
            $data['invite_code']='';
        }
        $this->ok($data);
    }




}
